﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

/*
    Socket1项目，主要弄清楚socket的初始化及怎样发送消息、接受消息
    Socket2项目，将Socket1项目稍微修改，实现客户端和服务端对话
*/
namespace Socket2.Client
{
    class Program
    {
        static void Main(string[] args)
        {
            IPAddress ip = IPAddress.Parse("127.0.0.1");
            IPEndPoint ipe = new IPEndPoint(ip, 5001);
            //1.建立一个Socket对象
            Socket socketClient = new Socket(AddressFamily.InterNetwork,
            SocketType.Stream, ProtocolType.Tcp);

            //2.去连接这个IP(没有Socket监听这个端口，就会报错)
            socketClient.Connect(ipe);
            Console.WriteLine("连接服务端" + ipe + "成功");

            //输入信息
            string inputMsg = string.Empty;
            //接受服务端发送过来的信息
            string message = string.Empty;
            while (true)
            {
                Console.WriteLine("请您输入信息给服务端（输入exit退出对话）：");
                inputMsg = Console.ReadLine();
                if (inputMsg.ToLower() == "exit")//退出对话
                {
                    break;
                }
                
                byte[] sendBytes = Encoding.UTF8.GetBytes(inputMsg);
                socketClient.Send(sendBytes);

                byte[] receiveBytes = new byte[2048];
                //客户端会一直等待服务器发送消息，否则不继续执行
                int byteLen = socketClient.Receive(receiveBytes,
                receiveBytes.Length, 0);
                message = Encoding.UTF8.GetString(receiveBytes, 0, byteLen);
                Console.WriteLine("服务器说：" + message);
            }

            //释放Socket占用的资源
            socketClient.Dispose();
            Console.ReadKey();


        }
    }
}
